package kamikaze.service.payment;

import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import kamikaze.ShoppingCart;
import kamikaze.entity.Order;
import kamikaze.entity.Payment;
import kamikaze.entity.User;
import kamikaze.support.HttpMethod;
import kamikaze.support.Service;
import kamikaze.support.ServiceConfig;
import kamikaze.support.ServiceContext;
import kamikaze.support.ServiceException;
import kamikaze.support.StringUtil;

@ServiceConfig(path = "payment.create", method = HttpMethod.POST)
public class CreatePaymentService implements Service {

	@Override
	public String serve(ServiceContext ctx) throws Exception {

		Order order = ShoppingCart.from(ctx).toOrder();
		
		ctx.getEntityManager().persist(order);
		
		User user = ctx.getUserSession().asUser();
		
		final Payment payment = new Payment();

		payment.setAmount(order.getTotalPrice());
		payment.setCardName(user.getCardName().toUpperCase());
		payment.setCardType(user.getCardType().name().toLowerCase());
		payment.setCardNumber(user.getCardNumber());
		payment.setExpm(new SimpleDateFormat("MM").format(user.getExpiredDate()));
		payment.setExpy(new SimpleDateFormat("yyyy").format(user.getExpiredDate()));
		payment.setTimestamp(order.getDate());
		
//		payment.setAmount(new BigDecimal(1));
//		payment.setCardName("DAVID+TAN");
//		payment.setCardType("mastercard");
//		payment.setCardNumber("5111111111111118");
//		payment.setExpm("03");
//		payment.setExpy("2013");
//		payment.setTimestamp(Calendar.getInstance().getTime());
		
		System.out.println ("payment.getPaymentGateway(): "+payment.getPaymentGateway());
		
		URL url = new URL(payment.getPaymentGateway().replace(" ", "+"));
		HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
		urlConn.setDoOutput(true);
		urlConn.setUseCaches(false);
		urlConn.connect();
		String strResponseCode = parseISToString((java.io.ByteArrayInputStream )urlConn.getContent()); 
		
//		System.out.println ("strResponseCode: "+strResponseCode);
		
		
		// {"result":"0","info":"pay success","refid":"20120426000008"} 	
		// {"result":"1"}
		// {"result":"2","info":"hash validation failed"}
		String[] resultJson = strResponseCode.trim().split("\\:");
		String result = resultJson[1].trim().substring(1,1);
		String info = (resultJson.length>=3)? resultJson[2].trim().substring(1,(resultJson[2].length()-2)) : " Please check the Card Credit Limit.";
		
//		System.out.println ("resultJson[0]:"+resultJson[0]+" resultJson[1]:"+resultJson[1]+"resultJson[2]:"+resultJson[2]);
		
		String resultPayment="";
		if (result.equals("0")) {
			String refid = (resultJson.length>=4) ? resultJson[3].trim().substring(1,(resultJson[3].length()-2)) : "";
			if (!refid.isEmpty()) {
				resultPayment = "Succesfully Paid with ref id:"+refid;
			} else {
				resultPayment = "Succesfully Paid.";
			}
			order.setStatus(Order.PaymentStatus.SUCCESFUL);
		} else if (result.equals("1")) {
			resultPayment = "Payment failed.";
			order.setStatus(Order.PaymentStatus.FAILED);
		} else {
			resultPayment = info;
			order.setStatus(Order.PaymentStatus.REJECTED);
		}
		
//		System.out.println ("Info: "+info+" resultPayment:"+resultPayment);
		
		ctx.getResponse().getWriter().print(resultPayment);

		return null;

	}
	
	public String parseISToString(java.io.InputStream is) {
		java.io.DataInputStream din = new java.io.DataInputStream(is);
		StringBuffer sb = new StringBuffer();
		try {
			String line = null;
			while ((line = din.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (Exception ex) {
			ex.getMessage();
		} finally {
			try {
				is.close();
			} catch (Exception ex) {
			}
		}
		return sb.toString();
	}
	
}
